
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Linq.Extensions;
using Abp.Extensions;
using Abp.Domain.Repositories;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using LTMCompanyName.YoyoCmsTemplate.Exam;
using LTMCompanyName.YoyoCmsTemplate.Exam.Dtos;
using LTMCompanyName.YoyoCmsTemplate.Exam.DomainService;
using LTMCompanyName.YoyoCmsTemplate.Authorization;
using LTMCompanyName.YoyoCmsTemplate.Exam.Authorization;
using LTMCompanyName.YoyoCmsTemplate.Exam.Colleges.Enum;
using LTMCompanyName.YoyoCmsTemplate.Enums;
using Microsoft.AspNetCore.Mvc.Rendering;

namespace LTMCompanyName.YoyoCmsTemplate.Exam
{
    /// <summary>
    /// 应用层服务的接口实现方法
	/// <see cref="StockCategory" />
    ///</summary>
    public class StockCategoryAppService : YoyoCmsTemplateAppServiceBase, IStockCategoryAppService
    {


        private readonly IStockCategoryManager _stockCategoryManager;

        private readonly IRepository<StockCategory, long> _entityRepository;

        private readonly IRepository<College, long> _collegeRepository;

        private readonly IRepository<Stock, long> _stockRepository;

        private readonly IRepository<StockSubmit, long> _stockSubmitRepository;

        private readonly IStockAppService _stockAppService;

        /// <summary>
        /// 构造函数
        ///</summary>
        public StockCategoryAppService(IStockCategoryManager stockCategoryManager, IRepository<StockCategory, long> entityRepository,
            IRepository<College, long> collegeRepository,
            IRepository<Stock, long> stockRepository, IStockAppService stockAppService, IRepository<StockSubmit, long> stockSubmitRepository)
        {
            _stockCategoryManager = stockCategoryManager;
            this._entityRepository = entityRepository;
            this._collegeRepository = collegeRepository;
            this._stockRepository = stockRepository;
            this._stockAppService = stockAppService;
            _stockSubmitRepository = stockSubmitRepository;
        }


        /// <summary>
        /// 获取的分页列表信息
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(StockCategoryPermissions.StockCategory_Query)]
        public async Task<PagedResultDto<StockCategoryListDto>> GetPaged(GetStockCategorysInput input)
        {
            var query = _entityRepository.GetAll().AsNoTracking().WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Name.Contains(input.FilterText)).Where(a => a.CreatorUserId == AbpSession.UserId);
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var stockCategoryList = await query
            .OrderBy(input.Sorting).AsNoTracking()
            .PageBy(input)
            .ToListAsync();

            //var stockCategoryListDtos = ObjectMapper.Map<List<StockCategoryListDto>>(stockCategoryList);

            // 包装列表需要显示的字段
            var stockCategoryListDtos = stockCategoryList.Select(item =>
            {
                return new StockCategoryListDto
                {
                    Id = item.Id,
                    Name = item.Name,
                    Sort = item.Sort,
                    Status = item.Status,
                    StatusName = ((Status)Convert.ToInt32(item.Status)).GetDescription(),
                    CollegeName = this._collegeRepository.Get(item.CollegeId)?.Name,
                    Description = item.Description
                };
            }).ToList();

            return new PagedResultDto<StockCategoryListDto>(count, stockCategoryListDtos);
        }

        /// <summary>
        /// 获得试卷
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<StockCategoryListDto>> Get(GetStockCategorysInput input)
        {
            var query = _entityRepository.GetAll().AsNoTracking().WhereIf(input.CollegeId > 0, a => a.CollegeId == input.CollegeId).WhereIf(!input.FilterText.IsNullOrWhiteSpace(), a => a.Name.Contains(input.FilterText)).Where(x=>x.Status=="1");
            // TODO:根据传入的参数添加过滤条件

            var count = await query.CountAsync();

            var stockCategoryList = await query
            .OrderBy(input.Sorting).AsNoTracking()
            .PageBy(input)
            .ToListAsync();

            //var stockCategoryListDtos = ObjectMapper.Map<List<StockCategoryListDto>>(stockCategoryList);

            // 包装列表需要显示的字段
            var stockCategoryListDtos = stockCategoryList.Select(item =>
            {
                return new StockCategoryListDto
                {
                    Id = item.Id,
                    Name = item.Name,
                    Sort = item.Sort,
                    Status = item.Status,
                    StatusName = ((Status)Convert.ToInt32(item.Status)).GetDescription(),
                    CollegeId = item.CollegeId.ToString(),
                    CollegeName = this._collegeRepository.Get(item.CollegeId)?.Name,
                    Description = item.Description,
                    StockCount = item.ShowCount > 0 ? item.ShowCount : _stockRepository.GetAll().AsNoTracking().Where(x => x.CategoryId == item.Id).Count()
                };
            }).ToList();

            return new PagedResultDto<StockCategoryListDto>(count, stockCategoryListDtos);
        }

        /// <summary>
        /// 通过指定id获取StockCategoryListDto信息
        /// </summary>
        [AbpAuthorize(StockCategoryPermissions.StockCategory_Query)]
        public async Task<StockCategoryListDto> GetById(EntityDto<long> input)
        {
            var entity = await _entityRepository.GetAsync(input.Id);

            var dto = ObjectMapper.Map<StockCategoryListDto>(entity);
            return dto;
        }

        /// <summary>
        /// 获取编辑 
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(StockCategoryPermissions.StockCategory_Create, StockCategoryPermissions.StockCategory_Edit)]
        public async Task<GetStockCategoryForEditOutput> GetForEdit(NullableIdDto<long> input)
        {
            var output = new GetStockCategoryForEditOutput();
            StockCategoryEditDto editDto;

            if (input.Id.HasValue)
            {
                var entity = await _entityRepository.GetAsync(input.Id.Value);
                editDto = ObjectMapper.Map<StockCategoryEditDto>(entity);
            }
            else
            {
                editDto = new StockCategoryEditDto();
            }
            output.CollegeList = this._collegeRepository.GetAllList().Where(x => x.Status == "1").Select(a => new SelectListItem()
            {
                Text = a.Name,
                Value = a.Id.ToString()
            }).ToList();
            output.StockCategory = editDto;
            return output;
        }


        /// <summary>
        /// 添加或者修改的公共方法
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(StockCategoryPermissions.StockCategory_Create, StockCategoryPermissions.StockCategory_Edit)]
        public async Task CreateOrUpdate(CreateOrUpdateStockCategoryInput input)
        {

            if (input.StockCategory.Id.HasValue)
            {
                await Update(input.StockCategory);
            }
            else
            {
                await Create(input.StockCategory);
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        [AbpAuthorize(StockCategoryPermissions.StockCategory_Create)]
        protected virtual async Task<StockCategoryEditDto> Create(StockCategoryEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = ObjectMapper.Map<StockCategory>(input);
            //调用领域服务
            entity = await _entityRepository.InsertAsync(entity);

            var dto = ObjectMapper.Map<StockCategoryEditDto>(entity);
            return dto;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        [AbpAuthorize(StockCategoryPermissions.StockCategory_Edit)]
        protected virtual async Task Update(StockCategoryEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _entityRepository.GetAsync(input.Id.Value);
            //  input.MapTo(entity);
            //将input属性的值赋值到entity中
            ObjectMapper.Map(input, entity);
            await _entityRepository.UpdateAsync(entity);
        }



        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [AbpAuthorize(StockCategoryPermissions.StockCategory_Delete)]
        public async Task Delete(EntityDto<long> input)
        {
            //删除试卷
            await _entityRepository.DeleteAsync(input.Id);

            //关联题目删除
            var idList = this._stockRepository.GetAll().Where(x => x.CategoryId == input.Id).Select(x => x.Id).ToList();
            if (idList != null)
            {
                await this._stockAppService.BatchDelete(idList);
            }
            //提交记录也要删除
            await _stockSubmitRepository.DeleteAsync(x => x.StockId == input.Id);
        }



        /// <summary>
        /// 批量删除StockCategory的方法
        /// </summary>
        [AbpAuthorize(StockCategoryPermissions.StockCategory_BatchDelete)]
        public async Task BatchDelete(List<long> input)
        {
            // 删除试卷
            await this._entityRepository.DeleteAsync(a => input.Contains(a.Id));

            //删除题目
            var idList = this._stockRepository.GetAll().Where(a => input.Contains(a.CategoryId)).Select(x => x.Id).ToList();
            if (idList != null)
            {
                await this._stockAppService.BatchDelete(idList);
            }

            //提交记录也要删除
            await _stockSubmitRepository.DeleteAsync(x => input.Contains(x.StockId));

        }
    }
}


